package com.adinnet.api.address.service.impl;

import com.adinnet.api.address.model.Address;
import com.adinnet.api.address.mapper.AddressMapper;
import com.adinnet.api.address.service.AddressService;
import com.adinnet.core.JsonResult;
import com.adinnet.core.redis.RedisConstant;
import com.adinnet.core.redis.RedisService;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * <p>
 * 省市区 服务实现类
 * </p>
 *
 * @author zYshuai
 * @since 2020-12-08
 */
@Service
public class AddressServiceImpl extends ServiceImpl<AddressMapper, Address> implements AddressService {


    @Autowired
    private AddressMapper addressMapper;

    @Autowired
    private RedisService redisService;



    /**
     * 省市区联动
     *
     * @return
     */
    @Override
    public List<Address> addressList() {
        // 先查询redis
        if (redisService.exists(RedisConstant.PROVINCE_KEY)) {
            Object val = redisService.get(RedisConstant.PROVINCE_KEY);
            return (List<Address>) val;
        }
        List<Address> provinceList = addressMapper.selectList(new QueryWrapper<Address>().eq("type", 1).eq("deleted", 0));
        List<Address> returnList = Lists.newArrayList();
        for (Address address : provinceList) {
            List<Address> cityList = addressMapper.selectList(new QueryWrapper<Address>()
                    .eq("type", 2).eq("deleted", 0).eq("province_code", address.getCode()));
            address.setAddresses(cityList);
            for (Address cityAddress : cityList) {
                List<Address> areaList = addressMapper.selectList(new QueryWrapper<Address>()
                        .eq("type", 3).eq("deleted", 0).eq("city_code", cityAddress.getCode()));
                cityAddress.setAddresses(areaList);
            }
            returnList.add(address);
        }
        redisService.set(RedisConstant.PROVINCE_KEY, returnList, RedisConstant.PROVINCE_KEY_TIME_OUT);
        return returnList;
    }
}
